<?php 

/**
* 数据库操作类
*/
class Model 
{
	public static $db;
	public $table;
	public $error;
	public $errno;
	public $where;
	function __construct($table=null)
	{
		if($table){
			$this->table=$table;
		}
		if(!self::$db){
			var_dump($table);
			try{
				self::$db = new PDO("mysql:host=".C('db_host').";dbname=".C('db_dbname').";charset=utf8",C('db_user'),C('db_password'));
		
			}catch(PDOException  $e ){
				echo "Error: ".$e;exit;
			}
		}
			

	}

	public function add($data)
	{
		// var_dump($data);
		
		$values = implode("','", $data);
		$keys = implode(',', array_keys($data));

		// var_dump($values);
		// var_dump($keys);

		$sql = "insert into ".$this->table." (".$keys.") values('".$values."')";

		return $this->exec($sql);
	}

	public function exec($sql)
	{
		$res =self::$db->exec($sql);

		if(!$res){
			$this->error=$this->db->errorInfo()[2];
			$this->errno=$this->db->errorCode();
		}
		return $res;
	}

	public function query($sql)
	{
		$res =self::$db->query($sql);

		if(!$res){
			$this->error=$this->db->errorInfo()[2];
			$this->errno=$this->db->errorCode();
			return false;
		}

		return $res->fetchAll(PDO::FETCH_ASSOC);
	}

	public function getError()
	{
		return "错误代码：".$this->errno."错误信息：".$this->error;
	}

	public function where($where)
	{
		$this->where = " where ".$where;
		return $this;
	}

	public function find()
	{
		$sql = "select * from ".$this->table.$this->where;
		return $this->query($sql);
	}

	public function save($data)
	{
		// var_dump($data);

		$str = '';

		foreach ($data as $k => $v) {
			$str .=$k."='".$v."',";
		}

		$str = rtrim($str,',');

		// var_dump($str);

		$sql ="update ".$this->table." set ".$str.$this->where;

		return $this->exec($sql);

	}

	public function delete($id=null)
	{
		$key = $this->getPri();

		if($id){
			$sql  = "delete from ".$this->table." where ".$key."=".$id;
		}else{
			$sql  = "delete from ".$this->table.$this->where;
		}

		return $this->exec($sql);
	}

	public function getPri()
	{
		$sql = "desc ".$this->table;

		$res = $this->query($sql);

		foreach ($res as $v) {
			if($v['Key']=='PRI'){
				return $v['Field'];
			}
		}
	}

	
}










 ?>